package com.whacos.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whacos.common.entity.Tree;
import com.whacos.common.enums.Constant;
import com.whacos.common.utils.BuildTree;
import com.whacos.modules.system.dao.SysDeptDao;
import com.whacos.modules.system.entity.SysDept;
import com.whacos.modules.system.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiongdun
 * @description SysDeptServiceImpl
 * @since 2018/11/17 17:11
 */
@CacheConfig(cacheNames = Constant.DEFAULT_CACHE_NAME)
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDept> implements SysDeptService {

    @Autowired
    private SysDeptDao sysDeptDao;

    /**
     * 查询所有部门
     * @param queryWrapper
     * @return
     */
    @Cacheable(cacheNames = Constant.DEFAULT_CACHE_NAME, key = "'sysDept'")
    @Override
    public List<SysDept> list(Wrapper<SysDept> queryWrapper) {
        return baseMapper.selectList(queryWrapper);
    }

    @Cacheable(cacheNames = Constant.DEFAULT_CACHE_NAME, key = "'sysDeptByTree'")
    @Override
    public Tree<SysDept> getTree() {
        List<Tree<SysDept>> trees = new ArrayList<>();
        List<SysDept> sysDeptList = sysDeptDao.selectList(null);
        for (SysDept sysDept : sysDeptList) {
            Tree<SysDept> tree = new Tree<>();
            tree.setId(sysDept.getId().toString());
            tree.setParentId(sysDept.getParentId().toString());
            tree.setText(sysDept.getDeptName());
            Map<String, Object> state = new HashMap<>();
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        return BuildTree.build(trees);
    }

    @CacheEvict(cacheNames = Constant.DEFAULT_CACHE_NAME, key = "'sysDept'")
    @Override
    public boolean updateById(SysDept entity) {
        return super.updateById(entity);
    }

    @CacheEvict(cacheNames = Constant.DEFAULT_CACHE_NAME, key = "'sysDept'")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    public boolean checkDeptHasUser(Long deptId) {
        //查询部门以及此部门的下级部门是否存在人员
        int result = sysDeptDao.selectDeptUserNumber(deptId);
        return result == 0;
    }

}
